package com.pig4cloud.pigx.contract.executer.position.migrator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pigx.common.customize.exception.MqNotAckException;
import com.pig4cloud.pigx.contract.entity.ContractPosition;
import com.pig4cloud.pigx.contract.enums.ContractPositionEnum;
import com.pig4cloud.pigx.contract.mapper.ContractPositionHistoryMapper;
import com.pig4cloud.pigx.contract.mapper.ContractPositionMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 历史仓位迁移
 *
 * @since 2022/9/20 16:22
 */
@Component
@AllArgsConstructor
public class PositionMigrator {

	private final ContractPositionMapper contractPositionMapper;
	private final ContractPositionHistoryMapper contractPositionHistoryMapper;

	public final String ERROR_MSG = "历史仓位迁移失败";

	/**
	 * 仓位id
	 *
	 * @param idList idList
	 * @since 2022/9/20 16:23
	 */
	public void migrator(List<Long> idList) {
		if (CollectionUtils.isEmpty(idList)) {
			return;
		}

		// 查询仓位
		QueryWrapper<ContractPosition> query = new QueryWrapper<>();
		query.lambda()
				.in(ContractPosition::getId, idList)
				.in(ContractPosition::getStatus, ContractPositionEnum.Status.CLOSE.getValue(),
						ContractPositionEnum.Status.LIQUIDATE.getValue());
		List<ContractPosition> list = contractPositionMapper.selectList(query);
		if (CollectionUtils.isEmpty(list)) {
			return;
		}

		// 历史仓位表新增
		if (contractPositionHistoryMapper.migrateBatch(list) != list.size()) {
			throw new MqNotAckException(ERROR_MSG);
		}

		// 获得实际迁移的仓位id
		List<Long> actualIdList = list.stream()
				.map(ContractPosition::getId)
				.collect(Collectors.toList());

		// 仓位表删除
		if (contractPositionMapper.deleteBatchIds(actualIdList) != list.size()) {
			throw new MqNotAckException(ERROR_MSG);
		}
	}
}
